/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import { data, follow } from "@mall/api-services"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import { RouteComponentProps, withRouter } from "react-router"
import Divider from "../components/divider"
import Flex from "../components/flex"
import NavBar from "../components/navbar"
import Icon from "../icon"

import "./follow-stores.scss"


interface DisplayFollowStoreProps extends RouteComponentProps {
  store: follow.FollowStore;
}

function DisplayFollowStoreComponent(props: DisplayFollowStoreProps) {

  const { history, store } = props
  return (
    <>
      <Flex className="display-follow-store"
            alignItems="center"
            onClick={() => history.push(`/stores/${store.id}`)}>
        <div className="store-logo">
          <img src={store.logoUrl} alt=""/>
        </div>
        <Flex direction="column" justifyContent="space-around">
          <span className="store-name">{store.name}</span>
        </Flex>
      </Flex>
      <Divider className="follow-store-divider"/>
    </>
  )
}

const DisplayFollowStore = withRouter(DisplayFollowStoreComponent)


interface FollowStoreListProps {
  customerId: string;
}


function FollowStoreList(props: FollowStoreListProps) {
  const { customerId } = props
  const [pageFollowStores, setPageFollowStores] = useState(data.PageList.empty() as data.PageList<follow.FollowStore>)
  const { elements } = pageFollowStores

  useEffect(() => {
    follow.FollowServiceV1.getFollowingStores().list().then(setPageFollowStores)
  }, [customerId])

  return (
    <div className="follow-store-list">
      {_.map(elements, store => <DisplayFollowStore key={store.id} store={store}/>)}
    </div>
  )
}

interface FollowStoresProps extends RouteComponentProps {

}

function FollowStores(props: FollowStoresProps) {
  const { history, match } = props

  const customerId = match.params["customer_id"]
  return (
    <div className="follow-stores">
      <NavBar className="follow-stores-nav-bar"
              left={<Icon type="left" onClick={() => history.goBack()}/>}>关注的店铺</NavBar>
      <FollowStoreList customerId={customerId}/>
    </div>
  )
}

export default withRouter(FollowStores)
